import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('../views/Home.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/clubs',
    name: 'ClubList',
    component: () => import('../views/ClubList.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/admin',
    name: 'Admin',
    component: () => import('../views/Admin.vue'),
    meta: { requiresAuth: true, role: '系统管理员' }
  },
  {
    path: '/clubadmin',
    name: 'ClubAdmin',
    component: () => import('../views/ClubAdmin.vue'),
    meta: { requiresAuth: true, role: '社团管理员' }
  },
  {
    path: '/my-clubs',
    name: 'MyClubs',
    component: () => import('../views/MyClubs.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/activities',
    name: 'ActivityList',
    component: () => import('../views/Activities.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/my-activities',
    name: 'MyActivities',
    component: () => import('../views/MyActivities.vue'),
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 添加验证状态缓存
let isVerifying = false;
let verifyPromise = null;

// 路由守卫
router.beforeEach(async (to, from, next) => {
  console.log('路由守卫触发 - 目标路由:', to.path);
  const userRole = localStorage.getItem('role');

  if (to.meta.requiresAuth) {
    console.log('该路由需要认证，开始验证token');
    
    try {
      const response = await fetch('http://localhost:8080/LZ/club/verify-token', {
        credentials: 'include',
        headers: {
          'Accept': 'application/json'
        }
      });
      const result = await response.json();
      
      console.log('Token验证结果:', result);
      if (result.code === 200) {
        console.log('Token有效。');
        if (to.meta.role) {
          console.log(`目标路由角色要求: ${to.meta.role}, 用户当前角色: ${userRole}`);
          if (userRole === to.meta.role) {
            console.log('角色匹配，允许访问');
            next();
          } else {
            console.log('角色不匹配，无权限访问此页面。');
            if (userRole === '系统管理员') {
              next('/admin');
            } else if (userRole === '社团管理员') {
              next('/clubadmin');
            } else {
              next('/home');
            }
          }
        } else {
          console.log('路由无特定角色要求，允许访问');
          next();
        }
      } else {
        console.log('Token验证失败或已过期，重定向到登录页');
        localStorage.removeItem('token');
        localStorage.removeItem('userInfo');
        localStorage.removeItem('role');
        localStorage.removeItem('username');
        localStorage.removeItem('avatarUrl');
        next('/login');
      }
    } catch (error) {
      console.error('Token验证请求失败:', error);
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      localStorage.removeItem('role');
      localStorage.removeItem('username');
      localStorage.removeItem('avatarUrl');
      next('/login');
    }
  } else {
    console.log('该路由不需要认证，直接通过');
    if ((to.name === 'Login' || to.name === 'Register') && userRole && localStorage.getItem('userInfo')) {
        console.log('用户已登录，尝试访问登录/注册页，重定向到对应主页');
        if (userRole === '系统管理员') {
            next('/admin');
        } else if (userRole === '社团管理员') {
            next('/clubadmin');
        } else {
            next('/home');
        }
        return;
    }
    next();
  }
});

export default router